<template>
  <div class="game">
    <div class="timers">
      <div class="tis" v-for="i in smlt" :key="i" :class="{ cur: i === smlt[ostIndex] }">X{{ i }}</div>
    </div>
    <div class="home" :style="style">
      <Cards v-for="(item, idx) in list" :key="item.id" :col="idx" :timer="timer" :row="row" :offset="item.offset"
        :height="height" :size="size" :types="types" ref="cards"></Cards>
    </div>
    <div class="btn" @click="play()">开始</div>
  </div>

</template>

<script>
import Cards from '../components/cards.vue';
import { sleep, groupArrayBySeven } from "../components/tooler"
// import anime from 'animejs/lib/anime.es.js';
// import conn from './conn';


export default {
  components: { Cards },
  data() {
    const w = 64;
    const h = 96;
    return {
      list: [],
      style: {},
      col: 5,
      row: 50,
      timer: 2400,
      types: 33,
      height: 7 * h,
      size: {
        x: w,
        y: h
      },
      ostIndex: 0,
      curList: [],
      smlt: [],
      smltId: -1,
      connData: null

    }
  },
  created() {
    this.style = {
      width: this.size.x * this.col + "px",
      height: this.height + "px"
    }
    for (let i = 0; i < this.col; i++) {
      this.list.push({
        id: i,
        offset: 0,
      })
    }
  },
  mounted() {
    this.start()
  },
  computed: {

  },
  methods: {
    async start() {
      //随机添加一组数据初始化
      const cards = this.$refs.cards;
      cards.forEach((item, idx) => {
        const ary = [];
        for (let i = 0; i < 7; i++) {
          // ary.push(Math.floor(Math.random() * 10))
          ary.push(i)
        }
        item.addData(ary, idx)
      })
    },
    async initData() {
      const conn = await this.loadData();
      this.connData = conn.data;
      const otherNum = 14;//补充个数
      const ost = this.connData.dt.ost;
      this.smlt = this.connData.dt.smlt;
      const aimList = Array(5).fill([]);
      ost.forEach(item => {
        const ary = groupArrayBySeven(item);
        ary.forEach((temp, i) => {
          aimList[i] = temp.concat(aimList[i]);

          // aimList[i] = temp;//测试
        })
      })

      //真实的牌型数据后面添加补充个数，做滚动效果
      aimList.forEach(item => {
        for (let i = 0; i < otherNum; i++) {
          item.push(1)
        }
      })

      // console.log("牌", aimList)

      await sleep(300)
      const cards = this.$refs.cards;
      cards.forEach((item, i) => {
        item.addData(aimList[i], i, this.ostIndex)
      })

      await sleep(900)
      cards.forEach((item, i) => {
        item.setMoveDistance(21)
      })
      this.getCurList()
    },
    getCurList() {
      this.curList = []
      const cards = this.$refs.cards;

      cards.forEach(card => {
        card.getItems().forEach(i => {
          this.curList.push(i)
        })
      })
    },
    async loadData() {
      return new Promise(resolve => {
        fetch('./data.txt')
          .then(response => {
            return response.json();
          })
          .then(data => {
            // console.log(data);
            resolve(data)
          })
          .catch(error => {
            // console.error('There was a problem fetching the data:', error);
            resolve(null)
          });
      })

    },
    async play(n) {
      if(!n){
        await this.initData()
      }
      // return
      const t = n ? n : this.timer;
      const cards = this.$refs.cards;

      cards.forEach(item => {
        item.setPlayTimer(t, !!n)
        item.run()
      })

      await sleep(t + 1200)

      this.check()
    },
    getWillRemoveItems(cards) {
      const temp = this.connData.dt.cn.conn[this.ostIndex];
      for (let i in temp) {
        // console.log("删除idx", temp[i])
        const ary = temp[i].map(item => {
          return this.curList.find(val => val.idx == item)
        })
        return ary
      }
      return []
    },
    resetPosition(cards) {
      // const cards = this.$refs.cards;
      cards.forEach((item) => {
        item.reset()
      })
    },
    setListIdx(cards) {
      cards.forEach((item, i) => {
        item.setListIdx(i)
      })
    },
    async check() {

      const cards = this.$refs.cards;
      // return

      //设置当前定格牌型idx
      this.setListIdx(cards);

      //获取需要删除的元素
      const removeList = this.getWillRemoveItems(cards);
      // console.log("removeList", removeList)
      await sleep(900)

      //设置删除元素选中样式
      removeList.forEach(item => item.choose(true));
      await sleep(1200)

      //重新定位元素，在屏幕下的元素依次移动到最顶部的位置
      // this.resetPosition(cards);
      this.ostIndex++;
      // this.initData();

      cards.forEach(card=>{
        card.clearOutside()
      })


      // await sleep(900)

      // console.log("removeList", removeList)
      //做消除动画
      if (removeList.length) {
        cards.forEach((item, i) => {
          //获取每一列需要消除的列表
          const removes = removeList.filter(v => v.col == i)
          // console.log(i, removes)
          //根据移除元素计算下落距离
          item.fixPosition(removes)
        })
        await sleep(200)
        this.play(300)
        this.smltId = -1
      }
      else {
        this.ostIndex = 0;
      }

    }
  },

}
</script>

<style scoped>
.home {
  display: flex;
  overflow-x: hidden;
  overflow-y: auto;
  margin: auto;
}

.timers {
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 10px;
}

.tis {
  flex: 1;
  background: #f0f0f0;
  color: #999;
  padding: 4px;
  text-align: center;
}

.btn {
  position: fixed;
  z-index: 1;
  left: 0;
  right: 0;
  margin: auto;
  bottom: 0;
  width: 50px;
  height: 50px;
  background: red;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  cursor: pointer;
}

.cur {
  background: #ff0000;
  color: #fff;
}
</style>
